package com.example.academic_affairs_system.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.academic_affairs_system.exception.SystemException;
import com.example.academic_affairs_system.model.vo.LoginResponseVO;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.security.GeneralSecurityException;

/**
 * 令牌处理工具类
 *
 * @author gzkemays
 * @since 2023/01/20 1:55 PM
 */
public class TokenUtils {
  static final String SECURITY = "u9Aj913MtP7J2Rq@Yzj_forum-gzkemays";

  public static String generateToken(LoginResponseVO vo) {
    try {
      return AesUtils.encrypt(JSONUtil.toJsonStr(vo), SECURITY);
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    }
  }

  public static LoginResponseVO parseToken(HttpServletRequest request) {
    String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (StrUtil.isBlank(header)) {
      throw new SystemException(-999, "请求异常，请重新登录", "无效密钥");
    }
    return parseToken(header);
  }

  public static LoginResponseVO parseToken(String token) {
    try {
      String decrypt = AesUtils.decrypt(token, SECURITY);
      if (decrypt == null) {
        throw new SystemException(-999, "请求异常，请重新登录", "无效密钥");
      }
      return JSONUtil.toBean(decrypt, LoginResponseVO.class);
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    }
  }
}
